package com.example.nna.main;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.nna.contain.containPage3;
import com.example.nna.listview.listViewCustom3;
import com.example.nna.listview.listViewCustom3.OnActionItemClickListener;
import com.example.nna.quickaction.ActionItem;
import com.example.nna.quickaction.QuickAction;

public class Page3 extends Page{
	private ArrayList<containPage3> ListContains;
	private listViewCustom3 adapter;
	private ImageButton mMenuGo;
	private TextView mTextNumPage;
	private RelativeLayout mMenuGoLayout;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.page2);
		super.onCreate(savedInstanceState);
		
		mList = (ListView)findViewById(R.id.mainlist);
		ListContains = new ArrayList<containPage3>();
		adapter = new listViewCustom3(mActivity,ListContains);
	    adapter.setSize(mTextSize);
	    mList.setAdapter(adapter);
	    mMenuTitle.setText(getIntent().getStringExtra("TITLE"));
	    //mParser.setUrl(URL+getIntent().getStringExtra("URL"));
	    mParser.setUrl("http://vozforums.com/showthread.php?t=3047921");
	    mTask.execute(TASK_GETDOC);
	    
	    adapter.setOnActionItemClickListener(new OnActionItemClickListener() {
			
			@Override
			public void onItemClick(int pos, int actionId) {
				// TODO Auto-generated method stub
				//toast(ListContains.get(pos).getText());
				toast(String.valueOf(pos));
				
				//mList.getChildAt(pos).
				//ActionPopup((View)mList.getItemAtPosition(pos));
			}
		});
	    
	}
	void ActionPopup(final View arg1){
		
	 	ActionItem replyItem 	= new ActionItem(1, "Reply", getResources().getDrawable(R.drawable.replyquickreply));
		ActionItem quoteItem 	= new ActionItem(2, "Quote", getResources().getDrawable(R.drawable.replyquote));
        ActionItem editItem 	= new ActionItem(3, "Edit", getResources().getDrawable(R.drawable.replyedit));
        final QuickAction mQuickAction 	= new QuickAction(mContext);
		mQuickAction.addActionItem(replyItem);
		mQuickAction.addActionItem(quoteItem);
		mQuickAction.addActionItem(editItem);
		mQuickAction.show(arg1);
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(QuickAction quickAction, int position, int actionId) {
				
			}
		});
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ListContains.clear();
		
		//adapter.notifyDataSetChanged();
	}
	@Override
	protected void updateSetFont(float value) {
		// TODO Auto-generated method stub
		super.updateSetFont(value);
		adapter.setSize(value);
		adapter.notifyDataSetChanged();
	}

	@Override
	void Parser() {
		ListContains.clear();
		String m_title = null;
    	containPage3 mContain;
    	Element mainElement;
    	mainElement = doc.select("div[align=center]").get(1);
    	Element eleLogin = mainElement.select("a[href=private.php]").first();
		//parsePage();
		//isSubscribe = isSubscribe();
    	mTextNumPage.setText(parsePage(GO_INDEXPAGE));
		if(eleLogin != null){
			String temp = mainElement.select("td[class=alt2]").get(0).select("a[href*=mem]").attr("href");
			temp = temp.split("=")[1];
			mUser.setUserId(temp);
	    	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
	    	String secToken;
	    	secToken = eleSecurity.attr("value");
	    	mUser.setToken(secToken);
		}
		String m_user,m_time,m_AvatartUrl;
		Elements eleTag1s = mainElement.select("td[id*=td_post]");

		Iterator<Element> iteTag1 = eleTag1s.iterator();
		while(iteTag1.hasNext()){
			mContain = new containPage3();
			Element eleTag1 = iteTag1.next();
			Element eleContain =  eleTag1.parent();
			Element eleAvatar = eleContain.previousElementSibling();
			Element eleTime = eleAvatar.previousElementSibling();
			m_AvatartUrl = eleAvatar.select("img[src*=avatars]").attr("src");
			m_user = eleAvatar.select("a[class=bigusername]").text();
			m_time = eleTime.text();
			Element elePostMessage = eleTag1.select("div[id*=post_message").first();
			if(elePostMessage!= null){
				mContain.setId(elePostMessage.attr("id").split("_")[2]);
		    	PaserPage3(elePostMessage,mContain,true,false);
				mContain.Info(m_user, m_time, null,m_AvatartUrl);
		    	new TaskDownloadImage().execute(URL+m_AvatartUrl,
		    			"-99;"+String.valueOf(ListContains.size()));
				ListContains.add(mContain);
			}
			adapter.notifyDataSetChanged();
		}
		
	}
	class TaskDownloadImage extends AsyncTask<String, Void, String>{
		Bitmap bitmap;
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			InputStream in = null;
			URL mUrl;
			HttpURLConnection conn;
			String url = params[0];
        	try {
				mUrl = new URL(url);
				conn = (HttpURLConnection)mUrl.openConnection();
				conn.setDoInput(true);
				conn.connect();
				in = conn.getInputStream();
				if(in != null){	
					BitmapFactory.Options op = new Options();
					op.inSampleSize = 2;
					bitmap = BitmapFactory.decodeStream(in,null,op);
				}else bitmap =  null;
				in.close();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log("cannot load image http" + url);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log("cannot load image http" + url);
			}
			return params[1];
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			String temp[] = result.split(";");
			int i = Integer.parseInt(temp[0]);
			int j = Integer.parseInt(temp[1]);
			if(i == -99){
				ListContains.get(j).setAvatar(bitmap);
			}else{
				ListContains.get(j).image.SetBitmap(i, bitmap);
				//ListContains.get(j).setAvatar(bitmap);
			}
			adapter.notifyDataSetChanged();
		}
		
	}
	private void PaserPage3(Element elePostMessage,containPage3 m_Contain,boolean write,boolean pre){
    	Element ele=null;
		if(elePostMessage.select("blockquote").first() != null){
			ele = elePostMessage.select("blockquote").first();
		}else{
			ele = elePostMessage;
		}
		if(ele != null){
			for (Node child : ele.childNodes()) {
				if(child instanceof Element){
					if(((Element)child).tagName().equals("div")){
						Element eleTemp = ((Element)child).select("div").first();
						m_Contain.addText("\n");
						PaserPage3(eleTemp,m_Contain,false,pre);
						m_Contain.addText("\n");
					}else if(((Element)child).tagName().equals("pre")){
						Element eleTemp = ((Element)child).select("pre").first();
						int start,end;
						start = m_Contain.getText().length();
						PaserPage3(eleTemp,m_Contain,false,true);
						end = m_Contain.getText().length();
						m_Contain.quote.add("", start,end);
					}else if(((Element)child).tagName().equals("ol")){
						Element eleTemp = ((Element)child).select("ol").first();
						PaserPage3(eleTemp,m_Contain,false,true);
					}else if(((Element)child).tagName().equals("li")){
						Element eleTemp = ((Element)child).select("li").first();
						PaserPage3(eleTemp,m_Contain,false,true);
					}else{
						if((((Element)child).select("table").first()) != null){
							Elements temp = ((Element)child).select("table");
							Element temp2,temp3;
							temp2 = temp.select("td[style*=border:1px inset]").first();
							if(temp2 != null){
								temp3 = temp2.select("div[style*=font-style:italic]").first();
								if(temp3!= null){
									int start,end;
									start = m_Contain.getText().length();
									m_Contain.addText(temp3.previousElementSibling().text() + "\n");
									PaserPage3(temp3,m_Contain,false,pre);
									end = m_Contain.getText().length();
									m_Contain.quote.add("", start, end);
									
								}else{
									int start,end;
									start = m_Contain.getText().length();
									PaserPage3(temp2,m_Contain,false,pre);
									end = m_Contain.getText().length();
									m_Contain.quote.add("", start, end);
								}
							}
						}else if(((Element)child).tagName().equals("img")){
							int start,end;
							String urlImage = (((Element)child).select("img[src]").attr("src"));
							if(urlImage.subSequence(0, 21).equals("http://vozforums.com/"))
								urlImage = urlImage.substring(21);
							if(urlImage.substring(0, 1).equals("/"))
								urlImage = urlImage.substring(1, urlImage.length());
							
							start = m_Contain.getText().length();
							end = start + 2;
							
							if(!urlImage.contains("http://"))
								m_Contain.image.add(urlImage, start, end, loadBitmapAssert(urlImage));
							else{
								m_Contain.image.add(urlImage, start, end, loadBitmapAssert("google.jpg"));
								new TaskDownloadImage().execute(urlImage,
						    			String.valueOf(m_Contain.image.sizeBitmap()-1)+";"+
						    			String.valueOf(ListContains.size()));
							}
							m_Contain.addText("aa");
							
						}else if(((Element)child).tagName().equals("br")){
							m_Contain.addText("\n");
						}else if(((Element)child).tagName().equals("b")){
							Element eleTemp = ((Element)child).select("b").first();
							int start,end;
							start = m_Contain.getText().length();
							PaserPage3(eleTemp,m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.type.add("", start, end,Typeface.BOLD_ITALIC);
						}else if(((Element)child).tagName().equals("u")){
							Element eleTemp = ((Element)child).select("u").first();
							int start,end;
							start = m_Contain.getText().length();
							PaserPage3(eleTemp,m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.typeU.add("", start, end);
						}else if(((Element)child).tagName().equals("font")){
							Element eleTemp = ((Element)child).select("font").first();
							int start,end;
							String mfont="while",msize="3";
							if(((Element)child).select("font[color]").first()!=null) 
								mfont = ((Element)child).select("font[color]").attr("color");
							if(((Element)child).select("font[size]").first()!=null) 
								msize = ((Element)child).select("font[size]").attr("size");
							start = m_Contain.getText().length();
							PaserPage3(eleTemp, m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.font.add("", start, end, mfont, Integer.parseInt(msize));
						}else if (((Element)child).tagName().equals("a")){
							String temp = ((Element)child).select("a[href]").attr("href");
							if(temp.contains("mailto:")){
								temp = temp.substring(7, temp.length());
							}else{
								temp = temp.substring(temp.indexOf("http"), temp.length());
							}
							temp=temp.replace("%3A",":");
							temp=temp.replace("%2F","/");
							temp=temp.replace("%3F","?");
							temp=temp.replace("%3D", "=");
							temp=temp.replace("%26", "&");
							int start,end;
							String tempText = ((Element)child).select("a[href]").text();
							start = m_Contain.getText().length();
							end = start + tempText.length();
							m_Contain.web.add(temp, start, end);
							m_Contain.addText(tempText);
						}else{
							m_Contain.addText(((Element)child).text());
							if(pre) m_Contain.addText("\n");
						}
					}
				}
			    if (child instanceof TextNode) {
			    	
			    	if(pre) m_Contain.addText(((TextNode) child).getWholeText());
			    	else m_Contain.addText(((TextNode) child).text());
			    }
			}
		}else{
			m_Contain.addText(elePostMessage.text());
		}
    }
	@Override
	void initUI() {
		// TODO Auto-generated methodstub
		super.initUI();
		mMenuGo = (ImageButton)findViewById(R.id.menu_go);
		mMenuGoLayout = (RelativeLayout)findViewById(R.id.panel_go);
		mTextNumPage = (TextView)findViewById(R.id.Go_NumPage);
		mMenuGo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				toast("click");
				if(mMenuGoLayout.getVisibility() == View.GONE)
					mMenuGoLayout.setVisibility(View.VISIBLE);
				else
					mMenuGoLayout.setVisibility(View.GONE);
			}
		});
		ImageButton mGo = (ImageButton)findViewById(R.id.Page2Page);
		ImageButton mNext = (ImageButton)findViewById(R.id.Page2Next);
		ImageButton mFirst = (ImageButton)findViewById(R.id.Page2First);
		ImageButton mPrev = (ImageButton)findViewById(R.id.Page2Previous);
		ImageButton mLast = (ImageButton)findViewById(R.id.Page2Last);
		
		mGo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//toast(parsePage(GO_REFRESH));
				mParser.setUrl(parsePage(GO_REFRESH));
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_GETDOC);
			}
		});
		mNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//toast(parsePage(GO_NEXT));
				mParser.setUrl(parsePage(GO_NEXT));
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_GETDOC);
				
			}
		});
		mFirst.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//toast(parsePage(GO_FIRST));
				mParser.setUrl(parsePage(GO_FIRST));
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_GETDOC);
			}
		});
		mPrev.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//toast(parsePage(GO_PREVIOUS));
				mParser.setUrl(parsePage(GO_PREVIOUS));
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_GETDOC);
			}
		});
		mLast.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//toast(parsePage(GO_LAST));
				mParser.setUrl(parsePage(GO_LAST));
				mTask.cancel(true);
				mTask = new TaskGetHtml();
				mTask.execute(TASK_GETDOC);
			}
		});
		
	}
}
